<template>
  <f7-page >
    <f7-navbar title="附件管理" back-link=""></f7-navbar>
    <f7-progressbar v-bind:progress="0" color="orange" id="inline-progressbar"></f7-progressbar>
    <f7-block-title>

      <f7-row>
      <f7-col width="30">
        <f7-label>文件上传</f7-label>
      </f7-col>
      <f7-col width="70">
        <f7-label class="callback"></f7-label>
      </f7-col>
      </f7-row>
      <div>
        <a href='javascript:;' class="a-upload">选择文件
          <input type="file"  @change="uploadAddition"  id="ufile" class="myFileUpload" />
        </a>
        <div class="showFileName"></div>
      </div>

    </f7-block-title>

    <f7-list media-list>
      <f7-list-item
        swipeout
        v-for="(item) in items"
        v-bind:key="item.id"
        v-bind:title="item.attachmentName"
        v-bind:after="item.updateDate"
        v-bind:subtitle="byteToKb(item.attachmentSize)"
        v-bind:text="item.attachmentType"
        @swipeout:open="saveCurItem(item)"
        @swipeout:deleted="delRecord">
        <f7-swipeout-actions right>
          <f7-swipeout-button close @click=" $refs.actionsOneGroup.open()">More</f7-swipeout-button>
        </f7-swipeout-actions>
      </f7-list-item>
    </f7-list>

    <f7-actions ref="actionsOneGroup">
      <f7-actions-group>
        <f7-actions-button @click="download">下载</f7-actions-button>
        <f7-actions-button @click="delRecord">删除</f7-actions-button>
      </f7-actions-group>
      <f7-actions-group>
        <f7-actions-button color="red">Cancel</f7-actions-button>
      </f7-actions-group>
    </f7-actions>
  </f7-page>
</template>

<script>
  export default {
    name: "additionList",
    data() {
      return {
        items: [],
        mainID: this.$f7route.params.id,
        accessory: {
          attachmentId: "",
          attachmentName: "",
          attachmentPath: "",
          attachmentRev: "",
          attachmentSize: 0,
          attachmentType: "",
          mainId:0,
        },
        fpath: "",
        curItem: null
      }
    },
    mounted() {
      this.$f7ready((f7) => {
        let that = this;
        let $$ = that.Dom7;
        f7.request.setup({
          headers: {
            'AccessToken': sessionStorage.getItem('accessToken'),
            'JSESSIONID': sessionStorage.getItem('userToken')
          }
        });
        f7.request.json(that.GLOBAL.RequestAddress + '/camel/rest/attachments', {
          'page': 1,
          'limit': 10,
          'jsonStr': '{mainId:' + that.mainID + '}',
          'start': '0',
        }, function (result) {
          if (result.totalCount > 0) {
            that.items = result.data;
          }
        });
        $$(".a-upload").on("change","input[type='file']",function(){

          let filePath = $$(this).val();
          let fileName = filePath.lastIndexOf("/");
          $$(".showFileName").html(fileName);

        })
      })
    },
    watch: {
      items: {
        handler() {
        },
        deep: true,
      }
    },
    methods: {
      getDataItems: function () {
        let that = this;
        let app = that.$f7;
        app.request.json(that.GLOBAL.RequestAddress + '/camel/rest/attachments', {
          'page': 1,
          'limit': 10,
          'jsonStr': '{mainId:' + that.mainID + '}',
          'start': '0',
        }, function (result) {
          if (result.totalCount >= 0) {
            that.items = result.data;
          }
        })
      },
      saveCurItem: function (item) {
        this.curItem = item;
      },
      notifyUploadSuccess: function () {
        let that = this;
        let app = that.$f7;
        let $$ = this.Dom7;
        app.request.postJSON(that.GLOBAL.RequestAddress + '/camel/rest/attachments',that.accessory, function (result) {
            $$('.callback').html(result.msg);
            that.getDataItems();
        })
      },
      uploadAddition: function () {
        let that = this;
        let $$ = this.Dom7;
        let mainID = that.mainID;
        let url = that.GLOBAL.RequestAddress + "/camel/rest/upload"
        that.setInlineProgress( 0);
        $$('.callback').html("");
        let file = document.getElementById('ufile').files[0];
        let formdata = new FormData();
        formdata.append("file", file);

        let xhr = new XMLHttpRequest();
        xhr.open("post", url);
        xhr.responseType = 'json';
        //回调
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            $$('.callback').html(xhr.response.msg);
            that.accessory.attachmentId = xhr.response.attachmentId;
            that.accessory.attachmentName = xhr.response.attachmentName;
            that.accessory.attachmentPath = xhr.response.attachmentPath;
            that.accessory.attachmentRev = xhr.response.attachmentRev;
            that.accessory.attachmentType = xhr.response.attachmentType;
            that.accessory.attachmentSize = xhr.response.attachmentSize;
            that.accessory.mainId = mainID;
            that.notifyUploadSuccess();
          }
        }
        //获取上传的进度
        xhr.upload.onprogress = function (event) {
          if (event.lengthComputable) {
            var percent = event.loaded / event.total * 100;
            that.setInlineProgress( percent);
          }
        }
        xhr.setRequestHeader('AccessToken', sessionStorage.getItem('accessToken'));
        xhr.setRequestHeader('JSESSIONID', sessionStorage.getItem('userToken'));
        //将formdata上传
        xhr.send(formdata);
      },
      delRecord: function () {
        let that = this;
        let url = that.GLOBAL.RequestAddress + "/camel/rest/attachments/" + that.curItem.id;

        fetch(url,
          {
            method: "delete",
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
              'AccessToken': sessionStorage.getItem('accessToken'),
              'JSESSIONID': sessionStorage.getItem('userToken')
            },
          }).then (response => response.json())
            .then(  result => {
              if (result.success == true) {
                that.getDataItems();
              }
              that.showAlert("提示",result.msg)
        }).catch(function (err) {
          console.log("Fetch错误", err)
        });

      },
      download: function () {
        let that = this;
        //let url = that.GLOBAL.RequestAddress + "/camel/rest/recruitapplys/workflow/startProcess";
        let url = that.curItem.attachmentPath;
        let app = that.$f7;

        fetch(url,
          {method: "get",
            headers: {
              'Access-Control-Allow-Origin':"*",
              "Access-Control-Allow-Credentials": "true",
              "Access-Control-Allow-Methods":"*",
              "Access-Control-Max-Age":"3600",
              'AccessToken': sessionStorage.getItem('accessToken'),
              'JSESSIONID': sessionStorage.getItem('userToken'),
            }}
        ).then (res => res.bolb().then(bolb => {
          let a = document.createElement('a');
          let url = window.URL.createObjectURL(blob);
          let filename = res.headers.get('Content-Disposition');
          a.href = url;
          a.download = filename;
          a.click();
          window.URL.revokeObjectURL(url);
        }));

        // app.request.JSON(url,{}, function (res, status, xhr) {
        //     res => res.bolb().then(bolb => {
        //         let a = document.createElement('a');
        //         let url = window.URL.createObjectURL(blob);
        //         let filename = res.headers.get('Content-Disposition');
        //         a.href = url;
        //         a.download = filename;
        //         a.click();
        //         window.URL.revokeObjectURL(url);
        // })



        //   .then(  result => {
        //     if (result.success == true) {
        //       that.getDataItems();
        //     }
        //     that.showAlert("提示",result.msg)
        //   }).catch(function (err) {
        //   console.log("Fetch错误", err)
        // });

        // 创建隐藏的可下载链接
        // let eleLink = document.createElement('a');
        // eleLink.download = that.curItem.attachmentName;
        // eleLink.style.display = 'none';
        //
        //   // 字符内容转变成blob地址
        //   eleLink.href = url;
        //   // 触发点击
        //   document.body.appendChild(eleLink);
        //   eleLink.click();
        //   // 然后移除
        //   document.body.removeChild(eleLink);
      },
      showAlert: function (title, text) {
        let that = this;
        let app = that.$f7;
        app.dialog.alert(text, title, () => {
          //that.$f7router.back();
        });
      },
      byteToKb: function (size) {
        let that = this;
        let kb = size / 1024;
        kb = Math.trunc(kb);
        return kb + " Kb";
      },
      setInlineProgress(value) {
        const self = this;
        const app = self.$f7;
        app.progressbar.set('#inline-progressbar', value);
      },
    }
  }
</script>

<style scoped>
  .a-upload {
    top:4px;
    padding: 4px 10px;
    height: 20px;
    line-height: 20px;
    position: relative;
    cursor: pointer;
    color: #888;
    background: #fafafa;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    display: inline-block;
    *display: inline;
    *zoom: 1
  }

  .a-upload  input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
    filter: alpha(opacity=0);
    cursor: pointer
  }

  .a-upload:hover {
    color: #444;
    background: #eee;
    border-color: #ccc;
    text-decoration: none
  }
</style>
